<template>
  <div class="category-manage-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <div class="search-form">
        <el-input
          v-model="searchForm.name"
          placeholder="分类名称"
          style="width: 200px; margin-right: 10px"
        />
        <el-select v-model="searchForm.status" placeholder="状态" style="width: 120px; margin-right: 10px">
          <el-option label="全部" :value="null" />
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button type="primary" @click="loadCategoryList">搜索</el-button>
        <el-button type="success" @click="openDialog('add')">添加分类</el-button>
      </div>
    </el-card>

    <!-- 分类列表 -->
    <el-card class="list-card">
      <el-table :data="categoryList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="openDialog('edit', scope.row)"
            >编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="updateCategoryStatus(scope.row)"
            >{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteCategory(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.type === 'add' ? '添加分类' : '编辑分类'"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="categoryForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

// 搜索表单
const searchForm = reactive({
  name: '',
  status: null
});

// 分类列表数据
const categoryList = ref([]);
const loading = ref(false);

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 对话框控制
const dialog = reactive({
  visible: false,
  type: 'add' // add or edit
});

// 分类表单
const categoryForm = reactive({
  id: null,
  name: '',
  description: '',
  status: 1
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

const categoryFormRef = ref(null);

// 加载分类列表
const loadCategoryList = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/news/category/list', {
      params: {
        current: pagination.current,
        size: pagination.size,
        name: searchForm.name || undefined,
        status: searchForm.status
      }
    });
    if (response.data.code === 200) {
      categoryList.value = response.data.data.records;
      pagination.total = response.data.data.total;
    } else {
      ElMessage.error(response.data.message || '获取分类列表失败');
    }
  } catch (error) {
    console.error('获取分类列表错误:', error);
    ElMessage.error('获取分类列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size;
  loadCategoryList();
};

const handleCurrentChange = (current) => {
  pagination.current = current;
  loadCategoryList();
};

// 打开对话框
const openDialog = (type, row = {}) => {
  dialog.type = type;
  dialog.visible = true;
  
  // 重置表单
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields();
  }
  
  if (type === 'edit' && row) {
    Object.keys(categoryForm).forEach(key => {
      if (row[key] !== undefined) {
        categoryForm[key] = row[key];
      }
    });
  } else {
    // 添加时默认值
    categoryForm.id = null;
    categoryForm.name = '';
    categoryForm.description = '';
    categoryForm.status = 1;
  }
};

// 提交表单
const submitForm = async () => {
  if (!categoryFormRef.value) return;
  
  await categoryFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      let response;
      if (dialog.type === 'add') {
        response = await axios.post('/news/category', {
          name: categoryForm.name,
          description: categoryForm.description,
          status: categoryForm.status
        });
      } else {
        response = await axios.put('/news/category', {
          id: categoryForm.id,
          name: categoryForm.name,
          description: categoryForm.description,
          status: categoryForm.status
        });
      }
      
      if (response.data.code === 200) {
        ElMessage.success(dialog.type === 'add' ? '添加成功' : '更新成功');
        dialog.visible = false;
        loadCategoryList();
      } else {
        ElMessage.error(response.data.message || (dialog.type === 'add' ? '添加失败' : '更新失败'));
      }
    } catch (error) {
      console.error(dialog.type === 'add' ? '添加分类错误:' : '更新分类错误:', error);
      ElMessage.error(dialog.type === 'add' ? '添加分类失败' : '更新分类失败');
    }
  });
};

// 更新分类状态
const updateCategoryStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1;
    const response = await axios.put('/news/category/status', {
      id: row.id,
      status: newStatus
    });
    
    if (response.data.code === 200) {
      ElMessage.success('状态更新成功');
      row.status = newStatus; // 直接更新当前行状态，避免重新加载整个列表
    } else {
      ElMessage.error(response.data.message || '状态更新失败');
    }
  } catch (error) {
    console.error('更新分类状态错误:', error);
    ElMessage.error('更新分类状态失败');
  }
};

// 删除分类
const deleteCategory = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此分类吗？删除后不可恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await axios.delete(`/news/category/${id}`);
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      loadCategoryList();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类错误:', error);
      ElMessage.error('删除分类失败');
    }
  }
};

// 页面加载时获取分类列表
onMounted(() => {
  loadCategoryList();
});
</script>

<style scoped>
.category-manage-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.list-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 